
import { RESPONSE_CODE } from '@/common/config';
import { handleRegionList } from '@/common/service';
import { DataItem, IRegionResponse, IResponseSuccess } from '@/typing';
import { makeAutoObservable } from 'mobx';

const formatData = (data: any[]): DataItem[] => {

    return data.map(item => {
        const children = item.children ? formatData(item.children) : undefined;
        return {
            value: item.code,
            label: item.name,
            children,
        };
    });
};
const generateRegionData = (REGION_DATA: any[]) => {

    if (REGION_DATA && REGION_DATA.length > 0) { }
    const regionDataT: DataItem[] = formatData(REGION_DATA);
    // console.log(regionData)
    // code转汉字大对象
    const codeToTextT: { [key: string]: string } = {};
    REGION_DATA.forEach(province => {
        codeToTextT[province.code] = province.name;
        // 将省份的code和name存入codeToText对象中
        province.children.forEach(city => {
            // 遍历城市
            codeToTextT[city.code] = city.name;
            // 将城市的code和name存入codeToText对象中
            if (city.children && city.children.length > 0) {
                city.children.forEach(area => {
                    // 遍历区域
                    codeToTextT[area.code] = area.name;
                });
            }

        });
    });

    return { regionDataT, codeToTextT };
}
 class RegionStore {
    regionDataT: DataItem[] = [];
    codeToTextT: { [key: string]: string } = {};
    constructor() {
        
      
        makeAutoObservable(this)
        // this.handleInitRegionList = this.handleInitRegionList.bind(this);
    }
    async handleInitRegionList() {
       
        const regionRes = await handleRegionList() as IResponseSuccess<IRegionResponse>
        if (regionRes.statusCode === RESPONSE_CODE.AJAX_SUCCESS && regionRes.data.code === RESPONSE_CODE.SUCCESS) {
            const regionDataList = regionRes.data.data;
            // console.log(regionDataList)
            if (regionDataList && regionDataList.length > 0) {
                const { regionDataT, codeToTextT } = generateRegionData(regionDataList)
                this.regionDataT = regionDataT;
                this.codeToTextT = codeToTextT;

            }



        }
    }


}
export default RegionStore